const mongoose = require('mongoose');
const FoodGI = require('../models/FoodGI');
const dotenv = require('dotenv');
const path = require('path');

// 加载环境变量
dotenv.config({ path: path.join(__dirname, '../.env') });

// 连接到MongoDB
const connectDB = async () => {
  try {
    const conn = await mongoose.connect(process.env.MONGO_URI, {
      useNewUrlParser: true,
      useUnifiedTopology: true
    });
    console.log(`MongoDB 连接成功: ${conn.connection.host}`);
    return conn;
  } catch (error) {
    console.error(`MongoDB 连接失败: ${error.message}`);
    process.exit(1);
  }
};

// 主食GI值数据
const stapleGIData = {
  "玉米糁": 42,
  "红薯": 54,
  "绿豆": 38,
  "大米": 83,
  "小米": 71,
  "糯米": 83,
  "黑米": 55,
  "玉米": 55,
  "红小豆": 44,
  "荞麦": 54,
  "薏米": 78,
  "燕麦片": 66,
  "通心粉": 46,
  "意大利面": 46,
  "白面条": 81,
  "粉丝": 35,
  "地瓜粉": 69,
  "绿豆粉": 37,
  "豌豆粉": 22,
  "红薯粉": 44,
  "米饭": 83,
  "糯米饭": 87,
  "黑米饭": 57,
  "玉米饭": 68,
  "大米粥": 86,
  "玉米粥": 68,
  "小米粥": 71,
  "绿豆粥": 38,
  "红豆粥": 44,
  "杂粮粥": 68,
  "八宝粥": 65
};

// 根据GI值分类
const getGICategory = (giValue) => {
  if (giValue <= 55) return 'low';
  if (giValue <= 69) return 'medium';
  return 'high';
};

// 基础营养数据（示例值，实际项目中应该使用准确数据）
const getNutrition = (name) => {
  // 不同食物类型的默认营养值
  const defaults = {
    // 碳水化合物类主食
    grains: {
      calories: 350,
      carbs: 75,
      protein: 10,
      fat: 2,
      fiber: 3,
      sugar: 1
    },
    // 薯类
    tubers: {
      calories: 120,
      carbs: 28,
      protein: 2,
      fat: 0.5,
      fiber: 4,
      sugar: 2
    },
    // 豆类
    legumes: {
      calories: 150,
      carbs: 25,
      protein: 10,
      fat: 1,
      fiber: 6,
      sugar: 1
    }
  };
  
  // 根据食物名称确定其类型
  let type = 'grains'; // 默认为谷物类
  
  if (['红薯', '地瓜粉', '红薯粉'].some(item => name.includes(item))) {
    type = 'tubers';
  } else if (['绿豆', '红小豆', '豌豆粉'].some(item => name.includes(item))) {
    type = 'legumes';
  }
  
  return defaults[type];
};

// 获取食物分类
const getCategory = (name) => {
  if (['红薯', '地瓜粉', '红薯粉'].some(item => name.includes(item))) {
    return 'tubers';
  } else if (['绿豆', '红小豆', '豌豆粉'].some(item => name.includes(item))) {
    return 'legumes';
  } else {
    return 'grains';
  }
};

// 获取是否为主食
const isStapleFood = (name) => {
  // 几乎所有项都是主食
  return true;
};

// 获取食物益处
const getBenefits = (name, giValue) => {
  const benefits = [];
  
  // 根据GI值添加标签
  if (giValue <= 55) {
    benefits.push('低GI值');
    benefits.push('血糖上升较慢');
  } else if (giValue <= 69) {
    benefits.push('中等GI值');
  } else {
    benefits.push('适合运动后补充能量');
  }
  
  // 根据食物类型添加特定标签
  if (name.includes('红薯')) {
    benefits.push('富含β-胡萝卜素');
    benefits.push('富含维生素A和C');
  } else if (name.includes('绿豆') || name.includes('红小豆')) {
    benefits.push('富含植物蛋白');
    benefits.push('助消化');
  } else if (name.includes('黑米')) {
    benefits.push('富含花青素');
    benefits.push('抗氧化');
  } else if (name.includes('燕麦')) {
    benefits.push('富含膳食纤维');
    benefits.push('有助降低胆固醇');
  } else if (name.includes('杂粮')) {
    benefits.push('营养更全面');
    benefits.push('膳食纤维丰富');
  }
  
  return benefits;
};

// 初始化食物GI值数据
const initializeFoodGIData = async () => {
  try {
    // 连接数据库
    await connectDB();
    
    // 检查是否已有数据
    const count = await FoodGI.countDocuments();
    if (count > 0) {
      console.log(`FoodGI数据库已初始化，包含${count}条记录`);
      process.exit(0);
    }
    
    // 准备批量导入的数据
    const foodsToInsert = [];
    
    for (const [name, giValue] of Object.entries(stapleGIData)) {
      const category = getCategory(name);
      const nutrition = getNutrition(name);
      const giCategory = getGICategory(giValue);
      const stapleFood = isStapleFood(name);
      const benefits = getBenefits(name, giValue);
      
      foodsToInsert.push({
        name,
        giValue,
        giCategory,
        category,
        nutrition,
        benefits,
        isStapleFood: stapleFood,
        notes: `GI值：${giValue}，属于${giCategory === 'low' ? '低' : giCategory === 'medium' ? '中' : '高'}GI食物`
      });
    }
    
    // 添加一些蛋白质食物
    const proteinFoods = [
      {
        name: '鸡胸肉',
        giValue: 0,
        giCategory: 'low',
        category: 'protein',
        nutrition: {
          calories: 165,
          carbs: 0,
          protein: 31,
          fat: 3.6,
          fiber: 0,
          sugar: 0
        },
        benefits: ['富含优质蛋白质', '低脂肪', '几乎不含碳水化合物'],
        isStapleFood: false,
        notes: '优质蛋白质来源，几乎不影响血糖'
      },
      {
        name: '豆腐',
        giValue: 15,
        giCategory: 'low',
        category: 'protein',
        nutrition: {
          calories: 76,
          carbs: 1.9,
          protein: 8,
          fat: 4.8,
          fiber: 0.3,
          sugar: 0.5
        },
        benefits: ['植物性蛋白质', '钙含量丰富', '低GI值'],
        isStapleFood: false,
        notes: '适合糖尿病患者的优质蛋白质来源'
      },
      {
        name: '三文鱼',
        giValue: 0,
        giCategory: 'low',
        category: 'protein',
        nutrition: {
          calories: 208,
          carbs: 0,
          protein: 20,
          fat: 13,
          fiber: 0,
          sugar: 0
        },
        benefits: ['富含欧米伽-3脂肪酸', '优质蛋白质', '对心血管健康有益'],
        isStapleFood: false,
        notes: '富含健康脂肪，对心血管和血糖控制有益'
      }
    ];
    
    // 添加一些蔬菜
    const vegetables = [
      {
        name: '西兰花',
        giValue: 15,
        giCategory: 'low',
        category: 'vegetables',
        nutrition: {
          calories: 34,
          carbs: 6.6,
          protein: 2.8,
          fat: 0.4,
          fiber: 2.6,
          sugar: 1.7
        },
        benefits: ['富含维生素C', '富含抗氧化物质', '低GI值'],
        isStapleFood: false,
        notes: '十字花科蔬菜，具有多种健康益处'
      },
      {
        name: '菠菜',
        giValue: 15,
        giCategory: 'low',
        category: 'vegetables',
        nutrition: {
          calories: 23,
          carbs: 3.6,
          protein: 2.9,
          fat: 0.4,
          fiber: 2.2,
          sugar: 0.4
        },
        benefits: ['富含铁质', '富含叶酸', '低卡路里'],
        isStapleFood: false,
        notes: '绿叶蔬菜，营养丰富且热量低'
      },
      {
        name: '黄瓜',
        giValue: 15,
        giCategory: 'low',
        category: 'vegetables',
        nutrition: {
          calories: 15,
          carbs: 3.6,
          protein: 0.7,
          fat: 0.1,
          fiber: 0.5,
          sugar: 1.7
        },
        benefits: ['水分充足', '低热量', '生津止渴'],
        isStapleFood: false,
        notes: '含水量高的蔬菜，有助于水分补充'
      }
    ];
    
    // 将蛋白质食物和蔬菜加入导入列表
    foodsToInsert.push(...proteinFoods, ...vegetables);
    
    // 批量插入数据
    await FoodGI.insertMany(foodsToInsert);
    
    console.log(`成功导入${foodsToInsert.length}条食物GI值数据`);
    process.exit(0);
  } catch (error) {
    console.error('导入食物GI值数据失败:', error);
    process.exit(1);
  }
};

// 执行初始化
initializeFoodGIData(); 